import { ApiResponse, Article, Channel } from "@/types/data";
import { HomeAction, RootThunkAction } from "@/types/store";
import request from "@/utils/request";
import { getChannel, hasToken, setChannel } from "@/utils/storage";

export function getUserChannels(): RootThunkAction {
  return async (dispatch) => {
    if (hasToken()) {
      const res = await request.get<ApiResponse<{channels: Channel[]}>>('/user/channels');
      dispatch({
        type: 'home/saveUserChannels',
        payload: res.data.data.channels
      });
    } else {
      //优先获取本地的值
      const channels = getChannel();
      if (channels.length > 0) {
        dispatch({
          type: 'home/saveUserChannels',
          payload: channels
        })
      } else {
        const res = await request.get<ApiResponse<{channels: Channel[]}>>('/user/channels');
        dispatch({
          type: 'home/saveUserChannels',
          payload: res.data.data.channels
        });
        // 把获取到的值再存入本地一份
        setChannel(res.data.data.channels);
      }
    }
  }
}

export function getAllChannels(): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{channels: Channel[]}>>('/channels');
    dispatch({
      type: 'home/saveAllChannels',
      payload: res.data.data.channels
    })
  }
}

export function changeActive(activeKey: number): HomeAction {
  return {
    type: 'home/changeAction',
    payload: activeKey
  }
}

export function addChannel(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    const {userChannels} = getState().home
    if (hasToken()) {
      // 如果登录了，发送请求保存频道信息
      // 注意 body 数据格式
      await request.patch('/user/channels', {
        channels: [channel]
      });
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setChannel([...userChannels, channel])
    }
    dispatch({
      type: 'home/saveUserChannels',
      payload: [...userChannels, channel]
    })
  }
}

export function delChannel(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    const {userChannels} = getState().home
    const newChannels = userChannels.filter((item) => {
      return item.id !== channel.id
    })
    //如果用户登录了，发送给后台
    if (hasToken()) {
      await request.put('/user/channels', {
        channels: newChannels,
      })
    } else {
      //如果用户没登录，保存在本地
      setChannel(newChannels)
    }
    dispatch({
      type: 'home/saveUserChannels',
      payload: newChannels
    })
  }
}

export function getArticleList(
  timestamp: number,
  channel_id: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{
      pre_timestamp: string
      results: Article[]
    }>>('/articles', {
      params: {
        timestamp,
        channel_id
      }
    })
    dispatch({
      type: 'home/getArticleList',
      payload: {
        timestamp: +res.data.data.pre_timestamp,
        results: res.data.data.results,
        channel_id,
      }
    })
  }
}

export function getNewList(
  timestamp: number,
  channel_id: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{
      pre_timestamp: string
      results: Article[]
    }>>('/articles', {
      params: {
        timestamp,
        channel_id
      }
    })
    dispatch({
      type: 'home/saveNewArticles',
      payload: {
        timestamp: +res.data.data.pre_timestamp,
        results: res.data.data.results,
        channel_id,
      }
    })
  }
}